#!/bin/sh

IMG_PATH=/mnt/cfg/secure.img
IMG_MOUNTPOINT=/mnt/cfg/param
TMP_PATH=/mnt/cfg/tmp_secure
KEY=`cat /mnt/cfg/testkey`

case $1 in
  start)
    e2fsck -y $IMG_PATH
    if [ -d $IMG_MOUNTPOINT ];then
      mount -t ext4 -o sync,rw $IMG_PATH $IMG_MOUNTPOINT
      echo $KEY | e4crypt add_key $IMG_MOUNTPOINT
      mount -t ext4 -o remount,sync,ro $IMG_MOUNTPOINT
    else
      mkdir -p $IMG_MOUNTPOINT
      mount -t ext4 -o sync,rw $IMG_PATH $IMG_MOUNTPOINT
      rm -rf  $IMG_MOUNTPOINT/*
      echo $KEY | e4crypt add_key $IMG_MOUNTPOINT
      echo "Moving secure data"
      cp -f $TMP_PATH/* $IMG_MOUNTPOINT
      find $TMP_PATH -type f -print0 | xargs -0 shred -f -u
      rm -rf $TMP_PATH
      sync
      mount -t ext4 -o remount,sync,ro $IMG_PATH $IMG_MOUNTPOINT
    fi
  ;;
  stop)
    sync
    umount $IMG_MOUNTPOINT
esac
